﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using NewFormatProject.Api.Admin.Controllers;
using NewFormatProject.Infrastructure.Atrributes;
using NewFormatProject.Infrastructure.Dto.Responses;
using NewFormatProject.Server.Interfaces;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Reflection;

namespace NewFormatProject.Api.Admin.Filters
{
    public class CheckLoginFilter:ActionFilterAttribute
    {
        private readonly ILoginServer _loginServer;
        private HttpContext _httpContext;
        private readonly IUserServer _userServer;
        public CheckLoginFilter(ILoginServer loginServer,IUserServer userServer)
        {
            _loginServer=loginServer;
            _userServer=userServer;
        }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            _httpContext=context.HttpContext;
            var action = context.ActionDescriptor as ControllerActionDescriptor;
            var attr = action.MethodInfo.GetCustomAttribute<CheckLoginAttribute>();
            // 如果没有特性则跳过检查
            if (attr==null)
            {
                return;
            }
            // 检查code
            string strUid = context.HttpContext.User.FindFirst("uid")?.Value;
            if (string.IsNullOrEmpty(strUid))
            {
                NotLogin();
                return;
            }
            int uid = Convert.ToInt32(strUid);
            string code= context.HttpContext.User.FindFirst("code")?.Value;
            if (_loginServer.GetLastLoginLog(uid).LlCode != code)
            {
                NotLogin();
                return;
            }
            (context.Controller as BaseController)._user = _userServer.Find(uid);

            return;
        }
        private void NotLogin()
        {
            _httpContext.Response.ContentType = "application/json;chartset=utf-8";
            _httpContext.Response.WriteAsync(JsonConvert.SerializeObject(ResponseApiDto.Fail("未登录")));
        }
    }
}
